<template>
  <div class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50">
    <div class="container mx-auto px-4 py-8">
      <!-- 页面标题 -->
      <div class="mb-8">
        <div class="flex justify-between items-center">
          <div class="text-center md:text-left">
            <div class="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-amber-600 to-orange-600 rounded-2xl mb-4 shadow-lg">
              <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
              </svg>
            </div>
            <h1 class="text-4xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent mb-2">编辑题目</h1>
            <p class="text-gray-600 text-lg">编辑题目信息</p>
          </div>
          <button
            class="px-6 py-3 bg-gradient-to-r from-gray-500 to-gray-600 text-white rounded-xl hover:from-gray-600 hover:to-gray-700 transition-all duration-200 transform hover:scale-105 shadow-lg hover:shadow-xl"
            @click="goBack"
          >
            <svg class="w-5 h-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
            </svg>
            返回
          </button>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoading" class="flex justify-center items-center py-16">
        <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-8 border border-white/20">
          <div class="flex items-center space-x-4">
            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            <span class="text-gray-600 font-medium">加载中...</span>
          </div>
        </div>
      </div>

      <!-- 编辑题目表单 -->
      <div v-else-if="question" class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-8 border border-white/20">
        <form @submit.prevent="handleSubmit" class="space-y-8">
          <!-- 基本信息 -->
          <div class="bg-gradient-to-r from-blue-50 to-indigo-50 p-6 rounded-2xl border border-blue-200/50">
            <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
              <svg class="w-5 h-5 mr-2 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              </svg>
              基本信息
            </h3>
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <!-- 题目标题 -->
              <div class="lg:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-2">题目标题 *</label>
                <input
                  v-model="form.title"
                  type="text"
                  required
                  class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                  placeholder="请输入题目标题"
                />
              </div>
            </div>
          </div>

          <!-- 题目内容 -->
          <div class="bg-gradient-to-r from-green-50 to-emerald-50 p-6 rounded-2xl border border-green-200/50">
            <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
              <svg class="w-5 h-5 mr-2 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
              </svg>
              题目内容
            </h3>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">题目描述 *</label>
              <MarkdownEditor
                v-model="form.content"
                class="min-h-[200px]"
                placeholder="请输入题目描述..."
              />
            </div>
          </div>

          <!-- 输入输出格式 -->
          <div class="bg-gradient-to-r from-purple-50 to-pink-50 p-6 rounded-2xl border border-purple-200/50">
            <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
              <svg class="w-5 h-5 mr-2 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
              </svg>
              输入输出格式
            </h3>
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">输入格式</label>
                <textarea
                  v-model="form.input_format"
                  rows="4"
                  class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent transition-all duration-200"
                  placeholder="请输入输入格式说明"
                ></textarea>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">输出格式</label>
                <textarea
                  v-model="form.output_format"
                  rows="4"
                  class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent transition-all duration-200"
                  placeholder="请输入输出格式说明"
                ></textarea>
              </div>
            </div>
          </div>

          <!-- 约束条件和样例 -->
          <div class="bg-gradient-to-r from-orange-50 to-red-50 p-6 rounded-2xl border border-orange-200/50">
            <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
              <svg class="w-5 h-5 mr-2 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
              </svg>
              约束条件和样例
            </h3>
            <div class="space-y-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">约束条件</label>
                <textarea
                  v-model="form.constraints"
                  rows="3"
                  class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-500 focus:border-transparent transition-all duration-200"
                  placeholder="请输入约束条件"
                ></textarea>
              </div>
              <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">样例输入</label>
                  <textarea
                    v-model="form.sample_input"
                    rows="4"
                    class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-500 focus:border-transparent transition-all duration-200"
                    placeholder="请输入样例输入"
                  ></textarea>
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">样例输出</label>
                  <textarea
                    v-model="form.sample_output"
                    rows="4"
                    class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-500 focus:border-transparent transition-all duration-200"
                    placeholder="请输入样例输出"
                  ></textarea>
                </div>
              </div>
            </div>
          </div>

          <!-- 代码模板 -->
          <div class="bg-gradient-to-r from-indigo-50 to-blue-50 p-6 rounded-2xl border border-indigo-200/50">
            <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
              <svg class="w-5 h-5 mr-2 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"></path>
              </svg>
              代码模板
            </h3>
            <div class="space-y-6">
              <!-- 语言选择 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-3">选择编程语言</label>
                <div class="flex flex-wrap gap-2">
                  <button
                    v-for="lang in programmingLanguages"
                    :key="lang.value"
                    type="button"
                    :class="[
                      'px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200',
                      selectedLanguage === lang.value
                        ? 'bg-gradient-to-r from-indigo-500 to-blue-600 text-white shadow-lg'
                        : 'bg-white/70 text-gray-700 border border-gray-200 hover:bg-indigo-50 hover:border-indigo-300'
                    ]"
                    @click="selectLanguage(lang.value as ProgrammingLanguage)"
                  >
                    {{ lang.label }}
                  </button>
                </div>
              </div>

              <!-- 基础代码模板 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">基础代码模板</label>
                <textarea
                  v-model="basecodeTemplates[selectedLanguage]"
                  rows="8"
                  class="w-full px-4 py-3 bg-gray-900 text-green-400 font-mono text-sm rounded-xl border border-gray-700 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all duration-200"
                  placeholder="请输入基础代码模板"
                ></textarea>
              </div>

              <!-- 运行代码 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">运行代码</label>
                <textarea
                  v-model="runCodeTemplates[selectedLanguage]"
                  rows="6"
                  class="w-full px-4 py-3 bg-gray-900 text-blue-400 font-mono text-sm rounded-xl border border-gray-700 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all duration-200"
                  placeholder="请输入运行代码"
                ></textarea>
              </div>
            </div>
          </div>

          <!-- 测试样例文件 -->
          <div class="bg-gradient-to-r from-teal-50 to-cyan-50 p-6 rounded-2xl border border-teal-200/50">
            <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
              <svg class="w-5 h-5 mr-2 text-teal-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
              </svg>
              测试样例文件
            </h3>
            <div class="space-y-4">
              <!-- 文件上传区域 -->
              <div
                class="border-2 border-dashed border-teal-300 rounded-xl p-8 text-center hover:border-teal-400 transition-colors duration-200 cursor-pointer"
                @click="triggerFileUpload"
                @dragover.prevent
                @drop.prevent="handleFileDrop"
              >
                <svg class="mx-auto h-12 w-12 text-teal-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path>
                </svg>
                <p class="text-teal-600 font-medium mb-2">点击上传或拖拽文件到此处</p>
                <p class="text-gray-500 text-sm">支持 .txt 文件，最大 1MB</p>
              </div>
              <input
                ref="fileInput"
                type="file"
                multiple
                accept=".txt"
                class="hidden"
                @change="handleFileSelect"
              />

              <!-- 已上传文件列表 -->
              <div v-if="testFiles.length > 0" class="space-y-2">
                <h4 class="text-sm font-medium text-gray-700">已上传文件：</h4>
                <div
                  v-for="(file, index) in testFiles"
                  :key="index"
                  class="flex items-center justify-between bg-white/70 rounded-lg p-3"
                >
                  <div class="flex items-center space-x-3">
                    <svg class="w-5 h-5 text-teal-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                    <span class="text-sm text-gray-700">{{ file.name }}</span>
                    <span class="text-xs text-gray-500">({{ formatFileSize(file.size) }})</span>
                  </div>
                  <button
                    type="button"
                    class="text-red-500 hover:text-red-700 transition-colors"
                    @click="removeFile(index)"
                  >
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- 其他设置 -->
          <div class="bg-gradient-to-r from-gray-50 to-slate-50 p-6 rounded-2xl border border-gray-200/50">
            <h3 class="text-lg font-semibold text-gray-900 mb-6 flex items-center">
              <svg class="w-5 h-5 mr-2 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
              </svg>
              其他设置
            </h3>
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">难度等级 *</label>
                <select
                  v-model="form.difficulty"
                  required
                  class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-gray-500 focus:border-transparent transition-all duration-200"
                >
                  <option value="">请选择难度</option>
                  <option value="Easy">简单</option>
                  <option value="Medium">中等</option>
                  <option value="Hard">困难</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">时间限制 (秒)</label>
                <input
                  v-model.number="form.time_limit"
                  type="number"
                  min="1"
                  class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-gray-500 focus:border-transparent transition-all duration-200"
                  placeholder="1000"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">内存限制 (MB)</label>
                <input
                  v-model.number="form.memory_limit"
                  type="number"
                  min="1"
                  class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-gray-500 focus:border-transparent transition-all duration-200"
                  placeholder="256"
                />
              </div>
            </div>
            <div class="mt-6">
              <label class="block text-sm font-medium text-gray-700 mb-2">题目来源</label>
              <input
                v-model="form.source"
                type="text"
                class="w-full px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-gray-500 focus:border-transparent transition-all duration-200"
                placeholder="请输入题目来源"
              />
            </div>
            <div class="mt-6">
              <label class="block text-sm font-medium text-gray-700 mb-2">标签</label>
              <div class="flex flex-wrap gap-2">
                <button
                  v-for="tag in availableTags"
                  :key="tag.id"
                  type="button"
                  :class="[
                    'px-3 py-1 rounded-full text-sm font-medium transition-all duration-200',
                    form.tag_ids.includes(tag.id)
                      ? 'bg-gradient-to-r from-blue-500 to-purple-600 text-white shadow-lg'
                      : 'bg-white/70 text-gray-700 border border-gray-200 hover:bg-blue-50 hover:border-blue-300'
                  ]"
                  @click="toggleTag(tag.id)"
                >
                  {{ tag.name }}
                </button>
              </div>
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="flex justify-end space-x-4">
            <button
              type="button"
              class="px-8 py-3 bg-gradient-to-r from-gray-500 to-gray-600 text-white rounded-xl hover:from-gray-600 hover:to-gray-700 transition-all duration-200 transform hover:scale-105 shadow-lg hover:shadow-xl"
              @click="goBack"
            >
              取消
            </button>
            <button
              type="submit"
              :disabled="isSubmitting"
              class="px-8 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-xl hover:from-blue-700 hover:to-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 transform hover:scale-105 shadow-lg hover:shadow-xl"
            >
              {{ isSubmitting ? '保存中...' : '保存修改' }}
            </button>
          </div>
        </form>
      </div>

      <!-- 错误状态 -->
      <div v-else class="text-center py-12">
        <div class="text-red-600 mb-4">
          <svg class="mx-auto h-12 w-12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
          </svg>
        </div>
        <h3 class="text-lg font-medium text-gray-900 mb-2">加载失败</h3>
        <p class="text-gray-600 mb-4">无法加载题目信息，请检查网络连接或刷新页面重试。</p>
        <button
          class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          @click="loadQuestion"
        >
          重新加载
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { questionApi } from '@/api/question'
import { useGlobalStore } from '@/stores/global'
import type { Tag, Question, ProgrammingLanguage } from '@/types'
import MarkdownEditor from '@/components/MarkdownEditor.vue'

const router = useRouter()
const route = useRoute()
const globalStore = useGlobalStore()

// 响应式数据
const isLoading = ref(true)
const isSubmitting = ref(false)
const question = ref<Question | null>(null)
const availableTags = ref<Tag[]>([])
const selectedLanguage = ref<ProgrammingLanguage>('cpp' as ProgrammingLanguage)
const basecodeTemplates = ref<Record<string, string>>({
  cpp: '',
  java: '',
  python: '',
  python3: '',
  javascript: '',
  go: '',
  rust: '',
  c: ''
})
const runCodeTemplates = ref<Record<string, string>>({
  cpp: '',
  java: '',
  python: '',
  python3: '',
  javascript: '',
  go: '',
  rust: '',
  c: ''
})
const testFiles = ref<File[]>([])

// 编程语言列表
const programmingLanguages = [
  { value: 'cpp', label: 'C++' },
  { value: 'java', label: 'Java' },
  { value: 'python', label: 'Python' },
  { value: 'javascript', label: 'JavaScript' },
  { value: 'go', label: 'Go' },
  { value: 'rust', label: 'Rust' }
]

// 表单数据
const form = reactive({
  title: '',
  content: '',
  input_format: '',
  output_format: '',
  constraints: '',
  sample_input: '',
  sample_output: '',
  difficulty: '' as 'Easy' | 'Medium' | 'Hard' | '',
  time_limit: 1000,
  memory_limit: 256,
  source: '',
  tag_ids: [] as number[]
})

// 方法
const loadQuestion = async () => {
  try {
    isLoading.value = true
    const questionId = Number(route.params.id)
    const response = await questionApi.getQuestion(questionId)
    
    if (response.data) {
      question.value = response.data
      
      // 填充表单数据
      form.title = response.data.title
      form.content = response.data.content
      form.input_format = response.data.input_format || ''
      form.output_format = response.data.output_format || ''
      form.constraints = response.data.constraints || ''
      form.sample_input = response.data.sample_input || ''
      form.sample_output = response.data.sample_output || ''
      form.difficulty = response.data.difficulty
      form.time_limit = response.data.time_limit || 1000
      form.memory_limit = response.data.memory_limit || 256
      form.source = response.data.source || ''
      form.tag_ids = response.data.tags?.map(tag => tag.id) || []
      
      // 填充代码模板
      if (response.data.basecode) {
        Object.keys(response.data.basecode).forEach(lang => {
          if (response.data!.basecode![lang]) {
            basecodeTemplates.value[lang] = response.data!.basecode![lang]!
          }
        })
      }
      
      if (response.data.run_code) {
        Object.keys(response.data.run_code).forEach(lang => {
          if (response.data!.run_code![lang]) {
            runCodeTemplates.value[lang] = response.data!.run_code![lang]!
          }
        })
      }
    }
  } catch (error) {
    console.error('加载题目失败:', error)
    console.error('加载题目失败')
  } finally {
    isLoading.value = false
  }
}

const loadTags = async () => {
  try {
    const response = await questionApi.getTags()
    if (response.data) {
      availableTags.value = response.data
    }
  } catch (error) {
    console.error('加载标签失败:', error)
  }
}

const selectLanguage = (lang: ProgrammingLanguage) => {
  selectedLanguage.value = lang
}

const toggleTag = (tagId: number) => {
  const index = form.tag_ids.indexOf(tagId)
  if (index > -1) {
    form.tag_ids.splice(index, 1)
  } else {
    form.tag_ids.push(tagId)
  }
}

const fileInput = ref<HTMLInputElement>()

const triggerFileUpload = () => {
  fileInput.value?.click()
}

const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files && target.files.length > 0) {
    handleFiles(Array.from(target.files))
  }
  // 重置input的value，确保下次选择文件时change事件能正常触发
  target.value = ''
}

const handleFileDrop = (event: DragEvent) => {
  if (event.dataTransfer?.files) {
    handleFiles(Array.from(event.dataTransfer.files))
  }
}

const handleFiles = (files: File[]) => {
  files.forEach(file => {
    if (file.type === 'text/plain' && file.size <= 1024 * 1024) {
      testFiles.value.push(file)
    } else {
      console.error(`文件 ${file.name} 格式不正确或文件过大`)
    }
  })
}

const removeFile = (index: number) => {
  testFiles.value.splice(index, 1)
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const handleSubmit = async () => {
  try {
    isSubmitting.value = true
    
    // 准备提交数据
    const submitData = {
      title: form.title,
      content: form.content,
      input_format: form.input_format,
      output_format: form.output_format,
      constraints: form.constraints,
      sample_input: form.sample_input,
      sample_output: form.sample_output,
      difficulty: form.difficulty as 'Easy' | 'Medium' | 'Hard',
      time_limit: form.time_limit,
      memory_limit: form.memory_limit,
      source: form.source,
      tag_ids: form.tag_ids,
      basecode: Object.fromEntries(
        Object.entries(basecodeTemplates.value).filter(([_, value]) => value.trim())
      ),
      run_code: Object.fromEntries(
        Object.entries(runCodeTemplates.value).filter(([_, value]) => value.trim())
      )
    }
    
    const questionId = Number(route.params.id)
    const response = await questionApi.updateQuestion(questionId, submitData)
    
    console.log('题目更新成功')
    router.push('/admin/questions')
  } catch (error) {
    console.error('更新题目失败:', error)
  } finally {
    isSubmitting.value = false
  }
}

const goBack = () => {
  router.push('/admin/questions')
}

// 生命周期
onMounted(async () => {
  await Promise.all([loadQuestion(), loadTags()])
})
</script>






